package com.niodata.dp.plugin.core;

import com.niodata.dp.api.common.DpTaskApi;
import com.niodata.dp.collection.WrappedStringKeyMap;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;

class DataSourceUtil {

  public static DataSource newDataSource(DpTaskApi api, String dsName, String dbName, String user) throws IOException, SQLException {
    WrappedStringKeyMap keyMap = api.getDbConfig(dsName, dbName, user);

    HikariConfig config = new HikariConfig();
    String jdbcUser = keyMap.getString("dataSource.user");
    String password = keyMap.getString("dataSource.password");
    String jdbcUrl = keyMap.getString("dataSource.jdbcUrl");
    config.setJdbcUrl(jdbcUrl);
    config.setUsername(jdbcUser);
    config.setPassword(password);
    String driver = keyMap.getString("dataSource.driver", null);
    if (driver == null || driver.isEmpty()) {
      driver = "com.mysql.cj.jdbc.Driver";
    }
    config.setDriverClassName(driver);
    HikariDataSource ds = new HikariDataSource(config);
    Connection connection = ds.getConnection();
    connection.createStatement().executeQuery("select 1+1");
    connection.close();
    return ds;
  }

  public static DataSource newDataSource(Properties properties) throws IOException, SQLException {
    HikariConfig config = new HikariConfig(properties);
    String user = properties.getProperty("dataSource.user");
    String password = properties.getProperty("dataSource.password");
    String jdbcUrl = properties.getProperty("dataSource.jdbcUrl");
    config.setJdbcUrl(jdbcUrl);
    config.setUsername(user);
    config.setPassword(password);
    String driver = properties.getProperty("dataSource.driver");
    if (driver == null || driver.isEmpty()) {
      driver = "com.mysql.cj.jdbc.Driver";
    }
    config.setDriverClassName(driver);
    HikariDataSource ds = new HikariDataSource(config);
    Connection connection = ds.getConnection();
    connection.createStatement().executeQuery("select 1+1");
    connection.close();
    return ds;
  }
}
